package com.guo.xiao.bing.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guo.xiao.bing.common.Config;
import com.guo.xiao.bing.dao.UserMapper;
import com.guo.xiao.bing.entity.User;
import com.guo.xiao.bing.entity.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User findUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public List<User> findUsersByExample(UserExample example) {
        return userMapper.selectByExample(example);
    }

    public PageInfo<User> pageFindUsersByExample(int currentPage, User user) {

        UserExample ue = new UserExample();
        UserExample.Criteria criteria = ue.createCriteria();
        if (user.getUsername() != null) {
            criteria.andUsernameLike("%" + user.getUsername() + "%");
        }
        if (user.getName() != null) {
            criteria.andNameLike("%" + user.getName() + "%");
        }
        if (user.getPhone() != null) {
            criteria.andPhoneLike("%" + user.getPhone() + "%");
        }
        ue.setOrderByClause("create_at desc");


        PageHelper.startPage(currentPage, Config.PAGE_SIZE);
        List<User> users = userMapper.selectByExample(ue);
        PageInfo<User> pageInfo = new PageInfo<>(users);

        return pageInfo;
    }

    public Integer saveUser(User user) {
        int i = userMapper.insert(user);
        return i;
    }

    public int updateUser(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    public Integer delete(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }
}
